package com.serializetool.handler;

import com.serializetool.Request;
import com.serializetool.SerializingUtil;
import com.serializetool.Validation;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class RpcDecoder extends ByteToMessageDecoder {
    AtomicInteger num = new AtomicInteger(0);

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if(in.readableBytes()<4){
            return;
        }
        int len = in.readInt();
        if(in.readableBytes()<len){
            in.resetReaderIndex();
            return;
        }
        System.out.println(num.incrementAndGet());
        byte[] bytes = new byte[len];
        in.readBytes(bytes);
        Request request = (Request) SerializingUtil.deserialize(bytes, Request.class);
        Validation.REQ_MES.getCode().equals(request.getMagicNum());
        if(Validation.REQ_MES.getCode().equals(request.getMagicNum())) out.add(request);
        in.markReaderIndex();
    }
}